<?php

namespace app\common\model;

use app\common\exception\ApiException;
use think\db\BaseQuery;
use think\Exception;
use think\facade\Session;
use utils\Jwt;

class StaffModel extends BaseModel
{
    //protected $autoWriteTimestamp = true;

    public $name = 'staff';

    function getDepartment(){
        return $this->hasOne('DepartmentModel','id','depart_id');
    }

    //获取客服对应的会员信息
    function getClient(){
        $info =$this->hasOne('ClientModel','id','client_id');
        return $info;
    }

    //通过客服id 获取他的uuid
    static function getUUid($uid,$admin_id){
        $uuid = ClientModel::findValue(['admin_id'=>$admin_id,'uid'=>$uid,'role'=>1],'id');
        return $uuid?:0;
    }

    //获取某个员工信息
    static function getInfo($uid){
        $field = 'id,admin_id,depart_id,name,mobile,head,priority,work_status,online';
        $info = self::with('getDepartment')
            ->where(['id'=>$uid])->field($field)
            ->find();
        if($info){
            $info = $info->toArray();
        }
        $info['role'] = 1;
        return $info;
    }

    //对员工信息 进行处理 统一数据格式
    static function handleUserInfo($info){
        if(empty($info)) return ;
        //防止重复处理
        if(isset($info['isHandle'])){
            return $info;
        }
        $new_info = [
            'id'=>$info['id'],
            'uuid'=>$info['uuid'],
            'uid'=>$info['id'],
            'nickname'=>$info['name'],
            'role'=>1,
            'headimg'=>$info['head'],
            'isHandle'=>1,
        ];
        $new_info['append'] = array_diff_key($info,$new_info);
        return $new_info;
    }


    //员工登录
    static function login($param){
        $info = self::findOne(['mobile'=>$param['username']]);
        if(empty($info)){
            throw new ApiException('账户不存在！');
        }
        if(xn_encrypt($param['password']) != $info['password']){
            throw new ApiException('账户或者密码不正确！');
        }
        if($info['status']==2){
            throw new ApiException('您的账户已禁用，请联系管理员处理！');
        }


        return $info;
    }

    //登陆成功 设置用户ticket信息
    static function setTicket($info){
        $new_info = self::handleUserInfo($info);
        $ticket = Jwt::getToken($new_info);
        //通过用户id 生成对应的ticket  主要是为了实现挤号的功能
//        $ticket = StaffTicketModel::setSticket($info['id']);

        Session::set('ticket', $ticket);
        return $ticket;
    }

    /**
     * 获取部门列表
     */
    static function getDepartmentList(){
        $list = DepartmentModel::findAll([
            'admin_id'=>ADMIN_ID,
        ],"id,name");

        $list =self::setListKey($list,'id','name');

        return $list;
    }

        //数据查询
    function getList($param){
        $order = $param['order']?:'id desc';
        $model = $this->order($order);
        $this->getListWhere($model,$param);
        $this->setAdmin($model,ADMIN_ID);
        $list = $model->paginate($param['limit']);
        return $list;
    }

    //获取导出数据
    function getExport($param,$fileName='',$type='xlsx'){
        $fileName = $fileName?:'数据表格';
        $fileName.='-'.date('YmdHis');
        //获取数据
        $order = $param['order']?:'id desc';
        $model = $this->order($order);
        $this->getListWhere($model,$param);
        $list = $model->select();
        if(empty($list)){
            return [];
        }
        foreach ($list as $k=>$v){
            $list[$k]['depart_id'] = $v->depart_id_text;
            $list[$k]['status'] = $v->status_text;
            $list[$k]['work_status'] = $v->work_status_text;
            if(is_numeric($v->create_time))$list[$k]['create_time'] = $v->create_time_text;
            if(is_numeric($v->update_time))$list[$k]['update_time'] = $v->update_time_text;
            if(is_numeric($v->login_time))$list[$k]['login_time'] = $v->login_time_text;

        }
        $list = $list->toArray();
        //得到表头
        $top = array_intersect_key(self::$fieldsList,$list[0]);
        //移除部分表头
        $top = array_diff_key($top,array_flip([]));
        //移除多余字段
        $list_new = [];
        foreach ($list as $k=>$v){
            $list_new[] = array_intersect_key($v,$top);
        }
        $list = $list_new;
        return [
            'fileName'=>$fileName,
            'top'=>$top,
            'data'=>$list,
            'type'=>$type,
        ];
    }

    function getNicknameAttr($val,$data){
        return $data['name'];
    }

    /**
     * 设置列表查询条件
     * @param BaseQuery $model
     * @param array $param
     * @return array
     */
    function getListWhere($model,$param=[]){
        if(empty($param)){
            return [];
        }
        $where = [];
            
        if($param['id']){
            $where['id'] = $param['id'];
        }
    
        if($param['depart_id']){
            $where['depart_id'] = $param['depart_id'];
        }
    
        if($param['name']){
            $where['name'] = $param['name'];
        }
    
        if($param['mobile']){
            $where['mobile'] = $param['mobile'];
        }
    
        if($param['head']){
            $where['head'] = $param['head'];
        }
    
        if($param['priority']){
            $where['priority'] = $param['priority'];
        }
    
        if($param['status']){
            $where['status'] = $param['status'];
        }
    
        if($param['work_status']){
            $where['work_status'] = $param['work_status'];
        }
    
        if($param['online']){
            $where['online'] = $param['online'];
        }
        
        if( $param['create_time']!='' ) {
            $create_time = explode('至',$param['create_time']);
            $date_time = [
                strtotime($create_time[0]),
                strtotime($create_time[1].' 23:59:59'),
            ];
            $model->whereBetween('create_time',$date_time);
        }
        
        if( $param['login_time']!='' ) {
            $create_time = explode('至',$param['login_time']);
            $date_time = [
                strtotime($create_time[0]),
                strtotime($create_time[1].' 23:59:59'),
            ];
            $model->whereBetween('login_time',$date_time);
        }


//        //检索查询
        if($param['search_key']){
            $where['id'] = $param['search_key'];
        }
        if($where){
            $model->where($where);
        }
    }

    //表字段别名
    public static $fieldsList = [
            'id'=>'id',
            'admin_id'=>'所属公司',
            'depart_id'=>'所属部门',
            'name'=>'姓名',
            'mobile'=>'手机号',
            'password'=>'密码',
            'head'=>'头像',
            'priority'=>'优先级',
            'status'=>'状态',
            'work_status'=>'工作状态',
            'online'=>'最后活动时间',
            'create_time'=>'创建时间',
            'update_time'=>'更新时间',
            'login_time'=>'最后登陆时间',

    ];

        //表字段状态
        public static $depart_idList = [
            '1'=>'默认部门',
    ];

    //所属部门获取器DepaIdText
    public function getDepartIdTextAttr($value,$data){
        $depart_idList = $this->getDepartmentList();
        if(strpos($data['depart_id'],',')){
            $arr = explode(',',$data['depart_id']);
            $arrText = [];
            foreach ($arr as $v){
                $arrText[]=$depart_idList[$v];
            }
            return join(',',$arrText);
        }else{
            return $depart_idList[$data['depart_id']]?:'--';
        }
    }

    public static $statusList = [
            '1'=>'启用',
            '2'=>'禁用',
    ];

    //状态获取器
    public function getStatusTextAttr($value,$data){
        if(strpos($data['status'],',')){
            $arr = explode(',',$data['status']);
            $arrText = [];
            foreach ($arr as $v){
                $arrText[]=self::$statusList[$v];
            }
            return join(',',$arrText);
        }else{
            return self::$statusList[$data['status']]?:'--';
        }
    }

    public static $work_statusList = [
            '1'=>'正常',
            '2'=>'忙碌',
            '3'=>'挂起',
    ];

    //工作状态获取器
    public function getWorkStatusTextAttr($value,$data){
        if(strpos($data['work_status'],',')){
            $arr = explode(',',$data['work_status']);
            $arrText = [];
            foreach ($arr as $v){
                $arrText[]=self::$work_statusList[$v];
            }
            return join(',',$arrText);
        }else{
            return self::$work_statusList[$data['work_status']]?:'--';
        }
    }

    public function getCreateTimeTextAttr($value,$data){
        if(is_numeric($data['create_time'])){
            return $data['create_time']>0 ? date(self::$formatTime,$data['create_time']) : '--';
        }else{
            return $data['create_time'];
        }
    }

    public function getUpdateTimeTextAttr($value,$data){
        if(is_numeric($data['update_time'])){
            return $data['update_time']>0 ? date(self::$formatTime,$data['update_time']) : '--';
        }else{
            return $data['update_time'];
        }
    }

    public function getLoginTimeTextAttr($value,$data){
        if(is_numeric($data['login_time'])){
            return $data['login_time']>0 ? date(self::$formatTime,$data['login_time']) : '--';
        }else{
            return $data['login_time'];
        }
    }

    //检查是否在线
    public function getOnlineTextAttr($value,$data){
        //如果存在 并且 5分钟内有活动  则判断在线
        if($data['online'] && $data['online']>time()-300){
            return '在线';
        }
        return '离线';
    }


}
